package com.aytbayev.asyl;

import java.util.Collections;
import java.util.LinkedList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ListStocks extends ListActivity {

	private ProgressDialog instr_ProgressDialog = null;
	private LinkedList<Instrument> instruments = null;
	private InstrumentAdapter instr_adapter;
	private Runnable viewStocks;
	private volatile Thread getInstrumentsThread;
	private volatile boolean stopListUpdate = false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stocks);

		this.instruments = new LinkedList<Instrument>();
		this.instr_adapter = new InstrumentAdapter(this,
				R.layout.instrument_row, instruments);
		setListAdapter(this.instr_adapter);

		ListView lv = getListView();			
		
		// this on long click
		registerForContextMenu(lv);
		
		// this on click
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Instrument o = instruments.get(position);
				Bundle bundle = new Bundle();
				bundle.putString("idKase", Integer.toString(o.getIdKase()));
				bundle.putString("typeGlass", Byte.toString(o.getTypeGlass()));
				bundle.putString("shortName", o.getShortName());
				Intent myIntent = new Intent(ListStocks.this, Stakan.class);
				myIntent.putExtras(bundle);
				ListStocks.this.startActivity(myIntent);
			}
		});
		
		
		
		viewStocks = new Runnable() {
			// @Override
			public void run() {
				while (true) {
					try {
						if (!stopListUpdate) {
							getInstruments();							
						}	
						Thread.sleep(10000);
					} catch (InterruptedException e) {
						Log.e("BACKGROUND_PROC", e.getMessage());
					}
				}

			}
		};
		if (getInstrumentsThread == null) {
			getInstrumentsThread = new Thread(null, viewStocks,
					"MagentoBackground");
			getInstrumentsThread.start();
		}
		instr_ProgressDialog = ProgressDialog.show(ListStocks.this,
				this.getString(R.string.wait),
				this.getString(R.string.loading), true);
	}
		
	@Override
	public void onResume() {
		super.onResume();
		stopListUpdate = false;
	}

	@Override
	public void onPause() {
		super.onPause();
		stopListUpdate = true;
	}

	private Runnable returnRes = new Runnable() {
		// @Override
		public void run() {
			if (instruments != null && instruments.size() > 0) {
				instr_adapter.notifyDataSetChanged();
				/*
				 * for(int i=0; i< instruments.size(); i++){ Instrument toAdd =
				 * instruments.get(i); instr_adapter.add(toAdd); }
				 */
			}
			instr_ProgressDialog.dismiss();
			// instr_adapter.notifyDataSetChanged();
		}
	};

	private void getInstruments() {
		DataManager.fillInstrumentsMobile(instruments, "3102035"); // TODO: pass actual
														// client id
		Collections.sort(instruments, new InstrumentComparator());
		runOnUiThread(returnRes);
	}

	private class InstrumentAdapter extends ArrayAdapter<Instrument> {
		private LinkedList<Instrument> items;

		public InstrumentAdapter(Context context, int textViewResourceId,
				LinkedList<Instrument> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); // TODO:
																										// read
																										// about
																										// getSystemService
				v = vi.inflate(R.layout.instrument_row, null);
			}
			Instrument o = items.get(position);
			if (o != null) {
				TextView shortname = (TextView) v.findViewById(R.id.shortname);
				TextView ask = (TextView) v.findViewById(R.id.ask);
				TextView bid = (TextView) v.findViewById(R.id.bid);
				// TextView last_transation = (TextView) v.findViewById(R.id.last_transation);
				if (shortname != null) {
					shortname.setText(o.getShortName());
				}
				Resources res = getResources();
				if (ask != null) {
					ask.setText(o.format(o.getBid())); // in web service ask/bid
														// are switched
					if (o.getAsk() != 0 && o.getBid() != 0) { // if both are 0,
																// skip
																// highlighting
						if (o.getBid() > o.getBidH()) {
							ask.setBackgroundColor(res.getColor(R.color.green));
						} else if (o.getBid() < o.getBidH()) {
							ask.setBackgroundColor(res.getColor(R.color.red));
						} else {
							ask.setBackgroundColor(res.getColor(R.color.black));
						}
					}
				}
				if (bid != null) {
					bid.setText(o.format(o.getAsk()));
					// highlight background if needed
					if (o.getAsk() != 0 && o.getBid() != 0) { // if both are 0,
																// skip
																// highlighting
						if (o.getAsk() > o.getAskH()) {
							bid.setBackgroundColor(res.getColor(R.color.green));
						} else if (o.getAsk() < o.getAskH()) {
							bid.setBackgroundColor(res.getColor(R.color.red));
						} else {
							bid.setBackgroundColor(res.getColor(R.color.black));
						}
					}
				}
				//if (last_transation != null) {
					//last_transation.setText(o.format(o.getLast()));
				//}
			}
			return v;
		}
	}
}